package com.mmall.example.atomic;


import com.mmall.annoations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 线程安全的 --> AtomicBoolean
 * 5000次请求，test方法只执行一次
 * Created by megan on 2018/3/18.
 */
@Slf4j
@ThreadSafe
public class AtomicBooleanExample {

    private static AtomicBoolean isHappened  =  new AtomicBoolean(false);

    /** 请求数 **/
    public static int clientTotal = 5000;

    /** 同时并发执行线程数 **/
    public static int threadTotal = 200;

    public static void main(String[] args) throws Exception {
        //定义一个线程池
        ExecutorService executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>(), r -> new Thread(r,"测试线程AtomicBoolean"));
        // 信号量，闭锁
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        // 模拟并发请求
        for(int i = 0; i < clientTotal; i ++){
            executorService.execute(() -> {
                try {
                    // 请求一个信号，如果信号量小于clientTotal，则阻塞
                    semaphore.acquire();
                    test();
                    // 释放一个信号
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        // 阻塞直到countDown 的次数为threadTotal
        countDownLatch.await();
        // 关闭线程池
        executorService.shutdown();
        log.info("isHappened:{}",isHappened);
    }

    private static void test(){
        if(isHappened.compareAndSet(false,true)){
            log.info("execute");
        }
    }

}
